from . import api_blueprint
from app.model.uploadhw import Uploadhw
from flask import request, json
from app import db


# get some uploaded homework
@api_blueprint.route('/uploadhw/<int:page_num>', methods=['GET'])
def get_uploadhw_by_page(page_num=1):
    stu_id = request.values.get('Stu_id')
    hw_id = request.values.get('HW_id')
    if stu_id is None and hw_id is None:
        return json.dumps({
            'status': 'error',
            'msg': 'Stu_id and HW_id are missing'
        }), 400
    if stu_id is None:
        record = Uploadhw.query.filter(Uploadhw.HW_id == hw_id).paginate(page_num, 10, False).items
    elif hw_id is None:
        record = Uploadhw.query.filter(Uploadhw.Stu_id == stu_id).paginate(page_num, 10, False).items
    else:
        record = Uploadhw.query.filter(Uploadhw.Stu_id == stu_id).filter(Uploadhw.HW_id == hw_id).paginate(page_num, 10, False).items
    return json.dumps(record, default=Uploadhw.to_json)


# delete upload homework
@api_blueprint.route('/uploadhw', methods=['DELETE'])
def delete_uploadhw():
    stu_id = request.values.get('Stu_id')
    hw_id = request.values.get('HW_id')
    if stu_id is None or hw_id is None:
        return json.dumps({
            'status': 'error',
            'msg': 'Stu_id or HW_id is missing'
        }), 400
    # print(courses)
    row = Uploadhw.query.filter(Uploadhw.Stu_id == stu_id).filter(Uploadhw.HW_id == hw_id).first()
    if row is None:
        return json.dumps({
            'status': 'error',
            'msg': 'target uploaded homework is not found'
        }), 404
    try:
        db.session.delete(row)
        db.session.commit()
    except Exception as e:
        print(e)
        return json.dumps({
            'status': 'error',
            'msg': str(e)
        }), 500
    # return cos_id
    return json.dumps({
        'status': 'success'
    })
